package com.yang.servlet;

import com.yang.pojo.Role;
import com.yang.service.RoleService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/DeleteRoleMultiServlet")
public class DeleteRoleMultiServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        RoleService roleService = new RoleService();
        List<Integer> fails = new ArrayList<>();
        String[] roleIds = request.getParameterValues("roleIds");
        for (int i = 0; i <roleIds.length; i++) {
            int roleId = Integer.parseInt(roleIds[i]);
            try {
                boolean b = roleService.deleteRole(roleId);
                if(b == false){
                    fails.add(roleId);
                }

            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }

        //提示信息
        String ids = "";
        for (Integer id : fails) {
            ids = ids + "," + id;
        }
        String tips = fails.size()==0?"<label style='color:green'>多个角色删除成功</label>":ids+"<label style='color:red'>删除失败</label>";
        request.setAttribute("tips",tips);
        try {
            ArrayList<Role> allRole = roleService.findAllRole();
            request.setAttribute("allRole",allRole);
            request.getRequestDispatcher("admin_role_list.jsp").forward(request,response);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
